package org.example.wikwok.controller;

//处理用户注册、登录、注销等HTTP请求。
//使用JWT或其他机制进行用户身份验证和会话管理。

import io.jsonwebtoken.Claims;
import jakarta.servlet.http.HttpServletResponse;
import net.minidev.json.JSONObject;
import org.example.wikwok.common.*;
import org.example.wikwok.pojo.Result;
import org.example.wikwok.pojo.User;
import org.example.wikwok.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;

import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.io.FileInputStream;
import java.io.InputStream;
import java.util.HashMap;
import java.util.Map;


@RestController
@RequestMapping(value = "/user")
public class UserController {
    @Autowired
    private UserService userService;

    @RequestMapping(value = "/register", method = RequestMethod.POST)
    public Result<Object> register(String username, String password) {
        JSONObject object = new JSONObject();
        if ("".equals(username)) {
            //用户名为空
            return Result.buildFailure(7777);
        }
        try {
            if (!userService.Register(username, password)) throw new Exception("1103");
            return Result.ok(object, 1101);
        } catch (Exception e) {
            //用户名已存在
            if (e.getMessage().contains("1103")) return Result.buildFailure(1103);
            return Result.buildFailure(1102);
        }
    }

    @RequestMapping(value = "/login", method = RequestMethod.POST)
    public Result<Object> login(String username, String password) throws Exception {
        JSONObject object = new JSONObject();
        if ("".equals(username)) {
            return Result.buildFailure(7777);
        }
        User user = userService.Login(username, password);
        if (user == null) {
            return Result.buildFailure(1112);
        } else {
            //生成token
            Map<String, Object> claims = new HashMap<>();
            claims.put("userId", user.getId());
            String token = JwtUtil.createJWT(
                    JwtProperties.getUserSecretKey(),
                    JwtProperties.getUserTtl(),
                    claims);
            object.put("token", token);
            return Result.ok(object, 1111);
        }
    }

    @RequestMapping(value = "/info", method = RequestMethod.GET)
    public Result<Object> getUserInfo(String token) {
        if (token == null || token.isEmpty()) {
            return Result.buildFailure(8888);
        }
        Claims claims = JwtUtil.parseJWT(JwtProperties.getUserSecretKey(), token);
        int userId = Integer.parseInt(claims.get("userId").toString());
        return Result.ok(userService.getUserInfo(userId), 1113);
    }

    @RequestMapping(value = "/update/password", method = RequestMethod.POST)
    public Result<Object> updateUserPassword(String token, String oldPassword, String newPassword) throws Exception {
        if (token == null || token.isEmpty()) {
            return Result.buildFailure(8888);
        }
        Claims claims = JwtUtil.parseJWT(JwtProperties.getUserSecretKey(), token);
        int userId = Integer.parseInt(claims.get("userId").toString());

        try{
            if (!userService.UpdateUserPassword(userId, oldPassword, newPassword)) {
                return Result.buildFailure(1302);
            }
        }catch (Exception e){
            //旧密码错误
            if(e.getMessage().contains("1303"))return Result.buildFailure(1303);
        }
        return Result.ok(null, 1301);
    }

    @RequestMapping(value = "/update/info", method = RequestMethod.POST)
    public Result<Object> updateUserInfo(String token, String username, MultipartFile file, String descrip) throws Exception {
        if (token == null || token.isEmpty()) {
            return Result.buildFailure(8888);
        }
        //判断文件是否为空
        if (file.isEmpty()) return Result.buildFailure(6666);
        Claims claims = JwtUtil.parseJWT(JwtProperties.getUserSecretKey(), token);
        int userId = Integer.parseInt(claims.get("userId").toString());
        String imgurl = System.currentTimeMillis() + "_" + username+"_"+file.getOriginalFilename();
        //如果用户头像上传文件夹不存在，则创建
        File dir = new File(UtilityClasses.getAvatarDir());
        if (!dir.exists()) {
            dir.mkdir();
        }
        if (!userService.UpdateUserInfo(userId, username, imgurl, descrip)) {
            return Result.buildFailure(1402);
        }
        file.transferTo(new File(UtilityClasses.getAvatarUploadDir() + imgurl));
        return Result.ok(null, 1401);
    }
    @RequestMapping(value = "/getImg", method = RequestMethod.GET)
    public void showImg(String token,String url, HttpServletResponse response) throws Exception {
     if (token == null || token.isEmpty()) return;
     Claims claims = JwtUtil.parseJWT(JwtProperties.getUserSecretKey(), token);
     int userId = Integer.parseInt(claims.get("userId").toString());
     File file = new File(UtilityClasses.getAvatarUploadDir() + url);
     if(!file.exists()){
      response.getOutputStream().close();
      return;
     }
     InputStream inStream=new FileInputStream(file);
     byte[] buffer = new byte[1024];
     int len;
     response.setContentType("image/jpeg");
     response.setHeader("Content-Disposition", "attachment;filename=" + file.getName());
     response.setHeader("Content-Length", String.valueOf(file.length()));
     response.setHeader("Connection", "Keep-Alive");
     response.setHeader("Accept-Ranges", "bytes");
     while ((len = inStream.read(buffer)) != -1) {
      response.getOutputStream().write(buffer, 0, len);
     }
     inStream.close();
     response.getOutputStream().flush();
     response.getOutputStream().close();
    }
@RequestMapping(value = "/logout", method = RequestMethod.POST)
    public void logout(int id, String name, String password, String imgUrl, String descrip) throws Exception {
        userService.Logout(id);
    }
}
